#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time, errno

class FileLockException(Exception):
    pass

class FileLock(object):
    def __init__(self, fileName, timeout=10, delay=.1):
        self.isLock = False
        self.lockFile = os.path.join(os.getcwd(), fileName+".lock")
        self.fileName = fileName
        self.timeout = timeout
        self.delay = delay
        
    def acquire(self, checkCancel):
        startTime = time.time()
        while not checkCancel():
            try:
                self.fd = os.open(self.lockFile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
                break
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise 
                if self.timeout != -1:
                    if (time.time() - startTime) >= self.timeout:
                        raise FileLockException("Timeout occured.")
                time.sleep(self.delay)
        if not checkCancel():
            self.isLock = True
        else:
            self.release()
        
    def release(self):
        if self.isLock:
            os.close(self.fd)
            os.unlink(self.lockFile)
            self.isLock = False
    
    def __exit__(self, type, value, traceback):
        print 'exit'
        self.release()
    
    def __del__(self):
        self.release()
        
    def __enter__(self):
        if not self.islock:
            self.acquire()
        return self
